package com.camera.road.servlet;

import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Date;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.camera.road.util.Util;
import com.google.gwt.core.client.GWT;

@SuppressWarnings("serial")
public class cameraPostServiceImpl extends HttpServlet {
    
    @SuppressWarnings("deprecation")
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        
        synchronized (this) {
            Util.index++;
            System.out.println(Util.index);
            int ContentLength = req.getContentLength();
//            byte[] remoteImg = new byte[ContentLength];
            GWT.log("Posted picture content is: "+ContentLength, null);

            String ident = req.getParameter("id");
            if( ident == null )
                ident = "no id";
            
            String seq = req.getParameter("sq");
            if( seq == null )
                seq = "no seq";

            String stamp = req.getParameter("timestamp");
            if( stamp == null )
                stamp = "local:"+ new Long(System.currentTimeMillis()).toString();
//            System.out.println("time is : " + stamp + "\r\nlenght is : " + ContentLength + "\r\n");
            
            if(Util.imgCache==null){
            	return;
            }
            
            InputStream imgData = req.getInputStream();
            try {
                BufferedInputStream in = new BufferedInputStream(imgData);         
                ByteArrayOutputStream out = new ByteArrayOutputStream(1024);         
                
//                System.out.println("Available bytes:" + in.available());         
                
                byte[] temp = new byte[1024];         
                int size = 0;         
                while ((size = in.read(temp)) != -1) {         
                    out.write(temp, 0, size);         
                }         
                in.close();         
                
                byte[] remoteImg = out.toByteArray();  
//                System.out.println("temoteImg length is : " + remoteImg.length + "\r\n");
//                imgData.read(remoteImg);
//                imgData.read(remoteImg);
//                imgData.close();
//                ImgPack img = new ImgPack();
//                img.id = ident;
//                img.seq = seq;
//                img.stamp = stamp;
//                img.image = remoteImg;
//                ImageCache.flushImg(img);
                Date dateTime = new Date(System.currentTimeMillis());
                String localTime = dateTime.toLocaleString();
                String date = localTime.split(" ")[0];
                String time = localTime.split(" ")[1];
                String baseUrl = req.getRealPath("photoData");
                File local = new File(baseUrl);
                if(!local.exists()){
                    local.mkdir();
                }
                File dateDir = new File(local.getPath() + "/" + date);
                if(!dateDir.exists()){
                    dateDir.mkdir();
                }
                File identDir = new File(dateDir.getPath() + "/" + ident);
                if(!identDir.exists()){
                    identDir.mkdir();
                }
                String hour = time.split(":")[0];
                File hourDir = new File(identDir.getPath() + "/" + hour);
                if(!hourDir.exists()){
                    hourDir.mkdir();
                }
                String name = hourDir.getPath() + "/" + getName(time) + "#" + seq + "#.jpg";
                writeToBytes(remoteImg, name);
//                test(name);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    
    private String getName(String time){
        String name = "";
        String[] tmp = time.split(":");
        for(int i=0;i<tmp.length;i++){
            name = name + tmp[i] + "_";
        }
        return name.substring(0, name.length()-1);
    }
    
    private void writeToBytes(byte bytes[], String fileName) {
        try {
            FileOutputStream fos = new FileOutputStream(fileName, true);
            fos.write(bytes);
            fos.flush();
            fos.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    
//    private void test(String fileName){
//        try {
//            FileInputStream fis = new FileInputStream("aa.jpg");
//            byte[] re = new byte[fis.available()];
//            fis.read(re);
//            fis.close();
//            String tmp = fileName.substring(0, fileName.length()-4);
//            FileOutputStream fos = new FileOutputStream(tmp + "ttt.jpg");
//            fos.write(re);
//            fos.flush();
//            fos.close();
//        } catch (FileNotFoundException e) {
//            // TODO Auto-generated catch block
//            e.printStackTrace();
//        } catch (IOException e) {
//            // TODO Auto-generated catch block
//            e.printStackTrace();
//        }
//    }
}
